<template>
  <div class="editor-test">
    <!-- 分栏布局 -->
    <div class="layout-container">
      <!-- 左侧：编辑器区域（手机宽度） -->
      <div class="editor-section">
        <div class="section-header">
          <h3>📝 编辑器</h3>
        </div>
        
        <div class="mobile-editor">
          <!-- WangEditor Vue 组件 -->
          <div class="wang-editor-container">
            <Toolbar
              class="toolbar"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              class="editor"
              v-model="html"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
              @onChange="onChange"
              @customPaste="handlePaste"
            />
          </div>
          
          <!-- <div class="editor-controls">
            <el-button size="mini" @click="getContent">获取内容</el-button>
            <el-button size="mini" @click="setTestContent">测试内容</el-button>
            <el-button size="mini" @click="clearContent">清空</el-button>
            <el-button size="mini" @click="insertText">插入文本</el-button>
          </div> -->
        </div>
      </div>
      
      <!-- 右侧：小程序预览区域 -->
      <div class="preview-section">
        <div class="section-header">
          <h3>📱 小程序预览效果<span style="color:red">（非小程序最终效果，仅供参考）</span></h3>
          
        </div>
        
        <div class="miniprogram-simulator">
          <div class="phone-frame">
            <div class="phone-screen">
              <div class="mini-app-header">
                <div class="status-bar">9:41</div>
                <div class="nav-bar">
                  <span class="back-btn">‹</span>
                  <span class="title">文章详情</span>
                  <span class="menu-btn">⋯</span>
                </div>
              </div>
              
              <div class="mini-app-content">
                <div class="article-container">
                  <!-- 富文本内容预览 -->
                  <div class="rich-text-preview" v-html="viewHtml"></div>
                  
                  <div class="empty-state" v-if="!html.trim() || html === '<p><br></p>' || html === '<p></p>'">
                    <div class="empty-icon">📝</div>
                    <div class="empty-text">暂无内容</div>
                    <div class="empty-tip">请在左侧编辑器中输入内容</div>
                  </div>
                </div>
              </div>
              
              <!-- <div class="mini-app-footer">
                <div class="tab-bar">
                  <div class="tab-item active">
                    <div class="tab-icon">🏠</div>
                    <div class="tab-text">首页</div>
                  </div>
                  <div class="tab-item">
                    <div class="tab-icon">📖</div>
                    <div class="tab-text">文章</div>
                  </div>
                  <div class="tab-item">
                    <div class="tab-icon">👤</div>
                    <div class="tab-text">我的</div>
                  </div>
                </div>
              </div> -->
            </div>
          </div>
        </div>
        
        <!-- HTML 源码预览 -->
        <div class="code-preview">
          <h4>HTML 源码</h4>
          <pre v-if="html"><code>{{ viewHtml }}</code></pre>
          <div v-else class="no-content">暂无内容</div>
        </div>
      </div>
    </div>
  </div>
</template>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
.editor-test {
  padding: 20px;
  padding-top:0px;
  max-width: 100%;
  margin: 0 auto;
}

/* 分栏布局 */
.layout-container {
  display: flex;
  gap: 30px;
  max-width: 1200px;
  margin: 0px auto;
}

.editor-section {
  flex: 0 0 375px; /* 固定手机宽度 */
}

.preview-section {
  flex: 1;
  min-width: 0;
}

/* 区块头部 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h3 {
  margin-top:10px;
  color: #2c3e50;
  font-size: 16px;
}

.status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  background: #e8f5e8;
  color: #52c41a;
  font-weight: 500;
}

.content-length {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  background: #f0f9ff;
  color: #1890ff;
  font-weight: 500;
}

/* 编辑器区域 */
.mobile-editor {
  border: 2px solid #e5e5e5;
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.wang-editor-container {
  border: none;
  background: #fff;
}

.toolbar {
  border-bottom: 1px solid #e5e5e5;
  background: #fafafa;
}

.editor {
  height: 550px;
  background: #fff;
}

.editor-controls {
  padding: 10px;
  background: #f5f5f5;
  border-top: 1px solid #e5e5e5;
  text-align: center;
}

.editor-controls .el-button {
  margin: 0 3px;
}

/* 小程序模拟器样式 */
.miniprogram-simulator {
  margin-bottom: 20px;
}

.phone-frame {
  width: 400px;
  margin: 0 auto;
  background: linear-gradient(145deg, #2c3e50, #34495e);
  border-radius: 25px;
  padding: 15px;
  box-shadow: 0 8px 30px rgba(0,0,0,0.3);
}

.phone-screen {
  background: #fff;
  border-radius: 18px;
  overflow: hidden;
  box-shadow: inset 0 0 10px rgba(0,0,0,0.1);
  height: 550px;
  display: flex;
  flex-direction: column;
}

/* 小程序头部 */
.mini-app-header {
  background: linear-gradient(180deg, #1890ff 0%, #40a9ff 100%);
  color: white;
}

.status-bar {
  text-align: center;
  font-size: 12px;
  padding: 8px 0 5px;
  font-weight: bold;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px 12px;
  font-size: 16px;
  font-weight: 500;
}

.back-btn, .menu-btn {
  font-size: 20px;
  cursor: pointer;
  width: 24px;
  text-align: center;
}

.title {
  flex: 1;
  text-align: center;
}

/* 小程序内容区 */
.mini-app-content {
  flex: 1;
  overflow-y: auto;
  background: #f5f5f5;
}

.article-container {
  padding: 15px;
  background: #fff;
  min-height: 100%;
}

.rich-text-preview {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.rich-text-preview p {
  margin: 8px 0;
}

.rich-text-preview h1, .rich-text-preview h2, .rich-text-preview h3 {
  margin: 15px 0 10px;
  color: #2c3e50;
}

.rich-text-preview ul, .rich-text-preview ol {
  margin: 10px 0;
  padding-left: 20px;
}

.rich-text-preview li {
  margin: 5px 0;
}

.rich-text-preview strong {
  font-weight: 600;
  color: #2c3e50;
}

.rich-text-preview blockquote {
  margin: 15px 0;
  padding: 10px 15px;
  border-left: 4px solid #1890ff;
  background: #f0f9ff;
  color: #666;
  font-style: italic;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 8px;
  color: #666;
}

.empty-tip {
  font-size: 12px;
  color: #999;
}

/* 小程序底部 */
.mini-app-footer {
  background: #fff;
  border-top: 1px solid #e5e5e5;
}

.tab-bar {
  display: flex;
  height: 50px;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-item.active {
  color: #1890ff;
}

.tab-item:hover {
  background: #f0f9ff;
}

.tab-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

.tab-text {
  font-size: 10px;
  font-weight: 500;
}

/* HTML 源码预览 */
.code-preview {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 15px;
}

.code-preview h4 {
  margin: 0 0 10px 0;
  color: #495057;
  font-size: 14px;
}

.code-preview pre {
  background: #fff;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 12px;
  font-size: 12px;
  line-height: 1.4;
  overflow: auto;
  max-height: 200px;
  margin: 0;
  color: #495057;
}

.no-content {
  color: #6c757d;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

/* wangEditor 样式覆盖 */
.wang-editor-container :deep(.w-e-toolbar) {
  padding: 8px;
  border-bottom: 1px solid #e5e5e5;
}

.wang-editor-container :deep(.w-e-text-container) {
  padding: 15px;
  font-size: 14px;
  line-height: 1.6;
  background: #fff;
}

.wang-editor-container :deep(.w-e-text-placeholder) {
  color: #bbb;
}

.wang-editor-container :deep(.w-e-text) {
  min-height: 200px;
  cursor: text;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .layout-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .editor-section {
    flex: none;
  }
  
  .mobile-editor,
  .phone-frame {
    width: 100%;
    max-width: 375px;
  }
}
</style>
<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default Vue.extend({
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  name: 'EditorTest',
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: this.value, // 用于编辑器内容
      viewHtml:this.htmlFormatter(this.value),
      toolbarConfig: {
        // 排除一些不常用的功能
         toolbarKeys : ["bold","color","headerSelect"]
      },
      editorConfig: { 
        placeholder: '请在这里输入内容...',
          MENU_CONF: {
           lineHeight: {
              lineHeightList: ['1', '1.8', '2', '2.5', '18px', '22px'], // 自定义行高选项
              defaultLineHeight: '1.8' // 默认行高
              }
          },  // 添加粘贴处理
      },
      mode: 'default'
    }
  },
  watch: {
    value(newVal) {
      if (newVal !== this.html) {
        this.html = newVal
      }
    }
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    
    onChange(editor) {
      // 内容变化时的回调
      const html = editor.getHtml()
      this.html = html
      this.viewHtml = this.htmlFormatter(html)
      this.$emit('input', html) // 关键：同步到父组件
    },
    // 添加到 methods 中
    handlePaste(editor, event) {
      // 阻止默认粘贴行为
      event.preventDefault()
      
      // 获取粘贴的纯文本内容
      const text = event.clipboardData.getData('text/plain')
      
      // 获取粘贴的HTML内容
      const html = event.clipboardData.getData('text/html')
      
      // 过滤HTML内容
      const filteredHtml = this.filterPastedHtml(html || text)
      
      // 插入过滤后的内容
      editor.dangerouslyInsertHtml(filteredHtml)
      
      // 返回true表示自己已处理，阻止默认粘贴行为
      return true
    },
      // 添加到 methods 中
    filterPastedHtml(html) {
      // 如果是纯文本，直接包裹在 p 标签中
      if (!html.includes('<')) {
        return `<p>${html}</p>`
      }
      
      // 移除样式标签
      html = html.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
      
      // 移除脚本标签
      html = html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
      
      // 保留有限的标签集合
      const allowedTags = ['p', 'br', 'b', 'strong', 'i', 'em', 'span', 'h1', 'h2', 'h3', 'ul', 'ol', 'li']
      
      // 创建临时DOM元素解析HTML
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = html
      
      // 递归处理所有节点
      const cleanNode = (node) => {
        // 如果是文本节点，直接返回
        if (node.nodeType === 3) {
          return true
        }
        
        // 检查元素节点
        if (node.nodeType === 1) {
          const tagName = node.tagName.toLowerCase()
          
          // 如果是不允许的标签，提取内容替换
          if (!allowedTags.includes(tagName)) {
            // 提取内容
            const content = node.textContent
            const wrapper = document.createElement('span')
            wrapper.textContent = content
            node.parentNode.replaceChild(wrapper, node)
            return false
          }
          
          // 移除所有on*事件
          for (let i = node.attributes.length - 1; i >= 0; i--) {
            const attrName = node.attributes[i].name
            if (attrName.startsWith('on') || attrName === 'style') {
              node.removeAttribute(attrName)
            }
          }
          
          // 递归处理子节点
          const childNodes = [...node.childNodes]
          childNodes.forEach(child => cleanNode(child))
        }
        
        return true
      }
      
      // 处理所有顶级节点
      const nodes = [...tempDiv.childNodes]
      nodes.forEach(node => cleanNode(node))
      
      // 获取清理后的HTML
      let cleanHtml = tempDiv.innerHTML
      
      // 应用标题转换
      cleanHtml = cleanHtml.replace(/<h1>(.*?)<\/h1>/gi, '<p style="font-size: 18px; font-weight: bold;">$1</p>')
      cleanHtml = cleanHtml.replace(/<h2>(.*?)<\/h2>/gi, '<p style="font-size: 16px; font-weight: bold;">$1</p>')
      
      return cleanHtml
    },
    
    getContent() {
      if (this.editor) {
        const html = this.editor.getHtml()
        const text = this.editor.getText()
        this.$message.success('内容已输出到控制台')
      } else {
        this.$message.error('编辑器未就绪')
      }
    },

    //format html中的值<h1>替换为字体18的p标签
    htmlFormatter(content){
      content = content.replace(/<h1>(.*?)<\/h1>/g, '<p style="font-size: 18px;">$1</p>')
      content = content.replace(/<h2>(.*?)<\/h2>/g, '<p style="font-size: 16px;">$1</p>')
      return content
    },
    
    setTestContent() {
      if (this.editor) {
        const testContent = `
          <h2>测试标题</h2>
          <p>这是一段<strong>粗体文字</strong>和<em>斜体文字</em>。</p>
          <p style="color: red;">这是红色文字</p>
          <p style="color: blue;">这是蓝色文字</p>
          <ul>
            <li>列表项目1</li>
            <li>列表项目2</li>
            <li>列表项目3</li>
          </ul>
          <blockquote>这是一个引用块，用于展示引用内容。</blockquote>
          <p>支持各种格式的文本编辑。</p>
        `
        this.html = testContent
        this.$message.success('测试内容已设置')
      } else {
        this.$message.error('编辑器未就绪')
      }
    },
    
    clearContent() {
      if (this.editor) {
        this.html = '<p><br></p>'
        this.$message.success('内容已清空')
      } else {
        this.$message.error('编辑器未就绪')
      }
    },
    
    insertText() {
      if (this.editor) {
        this.editor.insertText('插入的文本 ')
        this.$message.success('文本已插入')
      } else {
        this.$message.error('编辑器未就绪')
      }
    }
  },
  
  mounted() {
    console.log('组件已挂载，等待编辑器初始化...')
  },
  
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
 //   console.log('编辑器已销毁')
  },

})
</script>